package com.zzzzzz.oms.orderHead;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.core.datagrid.BaseQueryForm;
import com.zzzzzz.utils.page.Page;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zzzzzz.oms.GCS;
import com.google.common.collect.Lists;
import com.zzzzzz.plugins.shiro.ShiroUtils;
import com.zzzzzz.plugins.poi.ExportExcel;
import com.zzzzzz.plugins.poi.ImportExcel;

/**
 * @author hing
 * @version 1.0.0
 */
@Controller
public class OrderHeadWeb {

	@Resource
	public OrderHeadService orderHeadService;
	
	@Resource
	public OrderImportService importService;
	
	@Resource
	public OrderHeadDao orderHeadDao;

	// 打开界面
	@RequestMapping(value = "/orderHead/list", method = RequestMethod.GET)
	public String list() {
		return "oms/orderHead";
	}

	// 增加
	@RequestMapping(value = "/orderHead/save", method = RequestMethod.POST)
	@ResponseBody
	public BaseData save(@RequestBody @Valid OrderHead orderHead, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return new BaseData(GCS.ERRCD_PARAM);
		}
		orderHeadService.save(orderHead, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	// 更新状态，用于订单的生效和时效订单状态的改变
	@RequestMapping(value = "/orderHead/updStByIds", method = RequestMethod.POST)
	@ResponseBody
	public BaseData updStByIds(@RequestParam(value = "ids", required = true) List<Long> ids, @RequestParam(value = "status", required = true) String status) throws Exception {
		orderHeadDao.updStByIds(ids, status, ShiroUtils.findUser());
		return new BaseData("0");
	}	  
	
	// 查找一条数据
	@RequestMapping(value = "/orderHead/id/{id}", method = RequestMethod.GET)
	@ResponseBody 
	public BaseData findById(@PathVariable Long id) {
		OrderHead orderHead = orderHeadDao.findById(id);
		return new BaseData(orderHead, null);
	}
	
	// 动态查询
	@RequestMapping(value = "/orderHead/findListBy", method = RequestMethod.POST)
	@ResponseBody
	public BaseData findListBy(@RequestBody BaseQueryForm baseQueryForm) {
		Page page;
		List<OrderHead> list;
		BaseData baseData;
		if(baseQueryForm.getPageNb() == null && baseQueryForm.getPageSize() == null){
			list = orderHeadDao.findListBy(null,baseQueryForm.getFfMap(),ShiroUtils.findUser());
			baseData = new BaseData(list, null);
		}else{
			page = baseQueryForm.getPage();
			list = orderHeadDao.findListBy(page,baseQueryForm.getFfMap(),ShiroUtils.findUser());
			baseData = new BaseData(list, page.getTotal());
		}
		return baseData;
	}
	
	// 处理生效之后的数据
	@RequestMapping(value = "/orderHead/arrived", method = RequestMethod.POST)
	@ResponseBody
	public BaseData arrived(@RequestBody List<OrderHead> orderHeads,@RequestParam(value = "ids", required = true) List<Long> ids,@RequestParam(value = "vocations", required = true) List<String> vovations,@RequestParam(value = "code", required = true) String code) {
		orderHeadService.arrived(orderHeads,ids, vovations, ShiroUtils.findUser(), code);
		return new BaseData("0");
	}
	
	//配送异常情况登记
	@RequestMapping(value = "/orderHead/ps", method = RequestMethod.POST)
	@ResponseBody
	public BaseData updAccountById(@RequestParam(value = "id", required = true) Long id, @RequestParam(value = "account", required = true)String account) throws Exception {
		orderHeadDao.updAccountById(id, account, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	//退货时间
	@RequestMapping(value = "/orderHead/return", method = RequestMethod.POST)
	@ResponseBody
	public BaseData updRtimeById(@RequestParam(value = "ids", required = true) List<Long> ids,@RequestParam(value = "rtime", required = true)String rtime) throws Exception {
		orderHeadDao.updRtimeById(ids, rtime, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	// 删除订单
	@RequestMapping(value = "/orderHead/del", method = RequestMethod.POST)
	@ResponseBody
	public BaseData del(@RequestParam(value = "ids", required = true) List<Long> ids) {
		orderHeadDao.delByIds(ids);
		return new BaseData("0");
	}
	
	// 失效订单
	@RequestMapping(value = "/orderHead/back", method = RequestMethod.POST)
	@ResponseBody
	public BaseData back(@RequestParam(value = "ids", required = true) List<Long> ids, @RequestParam(value = "tempShipmentIds", required = true) List<Long> tempShipmentIds) {
		orderHeadService.back(ids, tempShipmentIds, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	// 导入
	@RequestMapping(value = "/orderHead/import", method=RequestMethod.POST)
    public String importExcel(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			if(StringUtils.isBlank(file.getOriginalFilename())){
				List<BaseData> list3 = new ArrayList<BaseData>();
				BaseData baseData = new BaseData();
				baseData.setErrMsg("您还没选择文件，请先选择需要导入的文件！");
				list3.add(baseData);
				redirectAttributes.addFlashAttribute("msg",list3);
			}else{
				ImportExcel importExcel = new ImportExcel(file, 1, 0);
				if(file.getOriginalFilename().contains("订单")){
					List<OrderHead> list = importExcel.getDataList(OrderHead.class);
					//long startTime=System.currentTimeMillis();
					List<BaseData> list1 = importService.batchAdd(list, ShiroUtils.findUser());
					//long endTime=System.currentTimeMillis(); //获取结束时间
					//System.out.println("程序运行时间： "+(endTime-startTime)+"ms");
					redirectAttributes.addFlashAttribute("msg", list1);						
				}else{
					List<BaseData> list2 = new ArrayList<BaseData>();
					BaseData baseData = new BaseData();
					baseData.setErrMsg("你导入模板有误，请重新选择模板导入。");
					list2.add(baseData);
					redirectAttributes.addFlashAttribute("msg", list2);
				}	
			}		
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "导入数据保存失败。");
			logger.warn("importExcel", e);
		}
		return "redirect:/msg";
    }
    
	// 下载导入模板
    @RequestMapping(value = "orderHead/import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单数据导入模板.xlsx";
    		List<OrderHead> list = Lists.newArrayList();
    		list.add(OrderHead.newTest());
    		new ExportExcel("订单数据导入模板", OrderHead.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "订单数据导入模板下载失败。");
			logger.warn("importFileTemplate", e);
		}
		return "redirect:/msg";
    }
    
    // 导出
    @RequestMapping(value = "/orderHead/export")
    public String exportFileTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {			
			Map<String, Object> params = WebUtils.getParametersStartingWith(request, null);
            String fileName = "订单数据.xlsx";           
            List<OrderHead> list = orderHeadDao.findListBy(null, params,ShiroUtils.findUser());
    		new ExportExcel("订单数据", CopyOfOrderHead.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "订单数据导出失败。");
			logger.warn("importFileTemplate", e);
		}
		return "redirect:/msg";
    }
    private static final Logger logger = LoggerFactory.getLogger(OrderHeadWeb.class);
}
